package com.zbs.framework.security.utils;

import com.zbs.framework.common.utils.CommonUtil;
import com.zbs.framework.common.utils.ErrEnum;
import com.zbs.framework.common.utils.ErrorAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author: Zbs
 * @createTime: 2021/3/1 18:02
 */
@Component
public class PasswordEncoderUtil {
    private static PasswordEncoder passwordEncoder;

    @Autowired
    public PasswordEncoderUtil(PasswordEncoder passwordEncoder){
        PasswordEncoderUtil.passwordEncoder = passwordEncoder;
    }

    public static String encode(String str){
        return passwordEncoder.encode(str);
    }

    public static boolean matches(String presentedPassword,String password){
        return passwordEncoder.matches(presentedPassword,password);
    }

    /**
     * 密码校验
     * @param userDetails 查出来的用户信息
     * @param presentedPassword 用户输入的密码
     * @throws AuthenticationException 抛出异常
     */
    public static void checkUserPassword(UserDetails userDetails, String presentedPassword) throws AuthenticationException {
        ErrorAssert.trimHasLength(presentedPassword, ErrEnum.USER_PWD_ERROR);
        final boolean matches = matches(CommonUtil.MD5_32(presentedPassword), userDetails.getPassword());
        ErrorAssert.isTrue(matches, ErrEnum.USER_PWD_ERROR);
    }

}
